#ifndef TCPSERVER_H
#define TCPSERVER_H

#include <QObject>
#include <QTcpServer>
#include <QHostAddress>
#include "clientmanager.h"
#include "threadpool.h"

class TcpServer : public QTcpServer {
    Q_OBJECT
public:
    explicit TcpServer(QObject *parent = nullptr);
    ~TcpServer();

    bool startServer(const QHostAddress &address = QHostAddress::Any, quint16 port = 12345);
    void stopServer();
    
    int clientCount() const;
    QList<qintptr> clientList() const;
    
    void broadcastMessage(const QString &message);
    void sendToClient(qintptr descriptor, const QString &message);

signals:
    void clientConnected(qintptr descriptor, const QString &info);
    void clientDisconnected(qintptr descriptor);
    void messageReceived(qintptr descriptor, const QString &message);
    void serverError(const QString &error);

protected:
    void incomingConnection(qintptr socketDescriptor) override;

private slots:
    void onClientConnected(qintptr descriptor, const QString &info);
    void onClientDisconnected(qintptr descriptor);
    void onMessageReceived(qintptr descriptor, const QString &message);
    void onErrorOccurred(qintptr descriptor, const QString &error);

private:
    ClientManager *m_clientManager;
    ThreadPool *m_threadPool;
    bool m_running;
};

#endif // TCPSERVER_H